package me.hgj.mvvm.network

import me.jessyan.retrofiturlmanager.RetrofitUrlManager
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory

/**
 * 作者　: hegaojian
 * 时间　: 2019/12/23
 * 描述　: 网络请求构建器基类
 */
abstract class BaseNetworkApi {

    private lateinit var retrofitBuilder: Retrofit.Builder

    fun createRetrofitBuilder(baseUrl: String) {
        retrofitBuilder = Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .client(mOkHttpClient)
    }

    /**
     * 获取api
     */
    fun <T> getApi(serviceClass: Class<T>): T {
        return setRetrofitBuilder(retrofitBuilder).build().create(serviceClass)
    }

/*    @Deprecated(message = "暂时弃用 改用getApi")
    fun <T> getApi(serviceClass: Class<T>, baseUrl: String): T {

        val retrofitBuilder = Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
        return setRetrofitBuilder(retrofitBuilder).build().create(serviceClass)
    }*/

    /**
     * 实现重写父类的setHttpClientBuilder方法，
     * 在这里可以添加拦截器，可以对 OkHttpClient.Builder 做任意操作
     */
    abstract fun setHttpClientBuilder(builder: OkHttpClient.Builder): OkHttpClient.Builder

    /**
     * 实现重写父类的setRetrofitBuilder方法，
     * 在这里可以对Retrofit.Builder做任意操作，比如添加GSON解析器，Protocol
     */
    abstract fun setRetrofitBuilder(builder: Retrofit.Builder): Retrofit.Builder

    /**
     * Http Client Builder
     */
    private val mOkHttpClient: OkHttpClient
        get() {
            val builder = RetrofitUrlManager.getInstance().with(OkHttpClient.Builder())
            return setHttpClientBuilder(builder).build()
        }
}



